package com.dms.modules.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dms.common.api.ApiResponse;
import com.dms.common.exception.BusinessException;
import com.dms.modules.order.entity.Order;
import com.dms.modules.order.service.OrderService;
import com.dms.modules.order.vo.OrderDetailVO;
import com.dms.modules.order.vo.OrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/api/v1/admin/orders")
@Api(tags = "平台订单管理")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class AdminOrderController {

    private final OrderService orderService;

    @GetMapping("/list")
    @ApiOperation("获取平台所有订单列表")
    public ApiResponse<IPage<OrderVO>> getAllOrders(
            @ApiParam("页码") @RequestParam(defaultValue = "1") @Min(1) Integer pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") @Min(1) Integer pageSize,
            @ApiParam("订单状态：0-待支付，1-已支付，2-已发货，3-已完成，4-已取消，5-退款中，6-已退款") 
            @RequestParam(required = false) Integer status,
            @ApiParam("商家ID") @RequestParam(required = false) Long merchantId,
            @ApiParam("用户ID") @RequestParam(required = false) Long userId,
            @ApiParam("开始时间") @RequestParam(required = false) LocalDateTime startTime,
            @ApiParam("结束时间") @RequestParam(required = false) LocalDateTime endTime) {
        try {
            // 构建查询条件
            LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
            if (status != null) {
                queryWrapper.eq(Order::getStatus, status);
            }
            if (merchantId != null) {
                queryWrapper.eq(Order::getMerchantId, merchantId);
            }
            if (userId != null) {
                queryWrapper.eq(Order::getUserId, userId);
            }
            if (startTime != null && endTime != null) {
                queryWrapper.between(Order::getCreateTime, startTime, endTime);
            }
            queryWrapper.orderByDesc(Order::getCreateTime);

            // 执行分页查询
            Page<Order> page = new Page<>(pageNum, pageSize);
            IPage<OrderVO> orderVOPage = orderService.getOrderVOPage(page, queryWrapper);
            return ApiResponse.success(orderVOPage);
        } catch (BusinessException e) {
            log.error("获取订单列表失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @ApiOperation("获取订单详情")
    public ApiResponse<OrderDetailVO> getOrderDetail(@PathVariable @NotNull Long id) {
        try {
            OrderDetailVO orderDetailVO = orderService.getAdminOrderDetail(id);
            return ApiResponse.success(orderDetailVO);
        } catch (BusinessException e) {
            log.error("获取订单详情失败，订单ID: {}", id, e);
            return ApiResponse.error(e.getMessage());
        }
    }

    @PostMapping("/{id}/force-refund")
    @ApiOperation("强制退款")
    public ApiResponse<Boolean> forceRefund(
            @PathVariable @NotNull Long id,
            @RequestParam @NotNull String reason) {
        try {
            log.info("管理员强制退款，订单ID: {}，原因: {}", id, reason);
            boolean result = orderService.forceRefund(id, reason);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("强制退款失败，订单ID: {}", id, e);
            return ApiResponse.error(e.getMessage());
        }
    }

    @PostMapping("/{id}/cancel")
    @ApiOperation("强制取消订单")
    public ApiResponse<Boolean> forceCancel(
            @PathVariable @NotNull Long id,
            @RequestParam @NotNull String reason) {
        try {
            log.info("管理员强制取消订单，订单ID: {}，原因: {}", id, reason);
            boolean result = orderService.forceCancel(id, reason);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("强制取消订单失败，订单ID: {}", id, e);
            return ApiResponse.error(e.getMessage());
        }
    }

    @GetMapping("/statistics")
    @ApiOperation("获取订单统计信息")
    public ApiResponse<Object> getOrderStatistics(
            @ApiParam("开始时间") @RequestParam(required = false) LocalDateTime startTime,
            @ApiParam("结束时间") @RequestParam(required = false) LocalDateTime endTime) {
        try {
            // TODO: 实现订单统计逻辑
            return ApiResponse.success(null);
        } catch (BusinessException e) {
            log.error("获取订单统计信息失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
} 